package com.yixun.qfbao.api.service.impl;

import com.google.common.collect.Lists;
import com.yixun.qfbao.api.service.PremisesRecommenderService;
import com.yixun.qfbao.api.service.ReportModelApiService;
import com.yixun.qfbao.api.service.V10BindService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.model.ReportModel;
import com.yixun.qfbao.model.ReportModelContent;
import com.yixun.qfbao.model.ReportModelInfo;
import com.yixun.qfbao.model.dto.ReportCopyRecordDto;
import com.yixun.qfbao.model.dto.ReportModelContentDto;
import com.yixun.qfbao.model.dto.ReportModelDto;
import com.yixun.qfbao.model.dto.ReportModelInfoDto;
import com.yixun.qfbao.model.enums.DefaultReportModelEnum;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.ModelTypeEnum;
import com.yixun.qfbao.model.enums.ReportModelShowStatusEnum;
import com.yixun.qfbao.service.ReportCopyRecordService;
import com.yixun.qfbao.service.ReportModelContentService;
import com.yixun.qfbao.service.ReportModelInfoService;
import com.yixun.qfbao.service.ReportModelService;
import com.yixun.qfbao.util.ChannelStringUtils;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ReportModelApiServiceImpl implements ReportModelApiService {

    @Autowired
    private ReportModelService reportModelService;
    @Autowired
    private ReportModelInfoService reportModelInfoService;
    @Autowired
    private CustomerPremisesService customerPremisesService;
    @Autowired
    private ReportModelContentService reportModelContentService;
    @Autowired
    private PremisesRecommenderService premisesRecommenderService;
    @Autowired
    private V10BindService v10BindService;
    @Autowired
    private ReportCopyRecordService reportCopyRecordService;
    @Autowired
    private PremisesService premisesService;

    private Logger logger = LoggerFactory.getLogger(ReportModelApiServiceImpl.class);

    /**
     * 更新报备模板
     * @param reqDto
     * @return
     */
    public EditReportModelResDto editReportModel(EditReportModelReqDto reqDto){
        EditReportModelResDto editReportModelResDto = new EditReportModelResDto();
        ReportModelDto reportModelDto = new ReportModelDto();
        try {
            if (reqDto.getId() != null) {
                reportModelDto.setId(reqDto.getId());
            }
            // 为空的情况
            if(StringUtils.isEmpty(reqDto.getModelColumn())){
                editReportModelResDto.setResult(ResultEnum.FAIL.getNo());
                editReportModelResDto.setResultMsg("模板名称不能为空");
                return editReportModelResDto;
            }
            
            //检查配置
            ReportModelDto selectReportModel = new ReportModelDto();
            selectReportModel.setDelFlag(DelFlagEnum.UNDEL.getNo());
            selectReportModel.setPremisesId(reqDto.getPremisesId());
//            selectReportModel.setModelColumn(reqDto.getModelColumn());
            List<ReportModel> list = reportModelService.selectListByDto(selectReportModel);
            
            // update by zilong.liu 避免出现后增加基础配置而导致基础配置无法增加的问题
            boolean existsColumn = false;
            Integer modelType = reqDto.getModelType();
            if(list.size() > 0){
            	existsColumn = list.stream().anyMatch(reportModel -> {
            		return reqDto.getModelColumn().equals(reportModel.getModelColumn());
            	});
            } else if (null != DefaultReportModelEnum.getByCode(reqDto.getModelColumn())){
            	existsColumn = true;
            }
            
            if(existsColumn){
        		editReportModelResDto.setResult(ResultEnum.FAIL.getNo());
        		editReportModelResDto.setResultMsg("已存在模板名称，不能更新");
        		return editReportModelResDto;
        	}

            if (null != DefaultReportModelEnum.getByCode(reqDto.getModelColumn())){
            	modelType = ModelTypeEnum.base_config.getCode();
            }
            
            reportModelDto.setPremisesId(reqDto.getPremisesId());
            reportModelDto.setModelColumn(reqDto.getModelColumn());
            reportModelDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
            reportModelDto.setModelAlias(reqDto.getModelAlias());
            reportModelDto.setShowFlag(reqDto.getShowFlag());
            if(modelType != null){
                reportModelDto.setModelType(modelType);
            }

            ReportModel model = reportModelService.editReportModel(reportModelDto);
            editReportModelResDto.setModel(model);
//            ReportModelDto s = new ReportModelDto();
//            s.setDelFlag(DelFlagEnum.UNDEL.getNo());
//            s.setPremisesId(reqDto.getPremisesId());
//            s.setModelType(ModelTypeEnum.customer_config.getCode());

            // 异步推送楼盘报备模板
            v10BindService.batchPushReportModel(reqDto.getPremisesId(), new ArrayList<>());
            editReportModelResDto.setResult(ResultEnum.SUCCESS.getNo());
        }catch (Exception e){
            editReportModelResDto.setResult(ResultEnum.FAIL.getNo());
            editReportModelResDto.setResultMsg("更新报备模板失败");
        }
        return editReportModelResDto;

    }


    /**
     * 楼盘报备模板修改
     * @param reqDto
     * @return
     */
    public DeleteReportModelResDto deleteReportModel(DeleteReportModelReqDto reqDto){
        DeleteReportModelResDto deleteReportModelResDto = new DeleteReportModelResDto();
        ReportModelDto reportModelDto = new ReportModelDto();
        if(reqDto.getId() == null){
            deleteReportModelResDto.setResult(ResultEnum.FAIL.getNo());
            deleteReportModelResDto.setResultMsg("报备模板id为空，删除失败");
            return deleteReportModelResDto;
        }
        reportModelDto.setId(reqDto.getId());
        reportModelDto.setDelFlag(DelFlagEnum.DEL.getNo());
        reportModelService.update(reportModelDto);
        deleteReportModelResDto.setResult(ResultEnum.SUCCESS.getNo());
        return deleteReportModelResDto;
    }

    /**
     * 楼盘报备上移下移
     * @param reqDto
     * @return
     */
    public MoveReportModelOrderResDto moveReportModelOrder(MoveReportModelOrderReqDto reqDto){
        MoveReportModelOrderResDto moveReportModelOrderResDto = new MoveReportModelOrderResDto();
        ReportModelDto reportModelDto = new ReportModelDto();
        reportModelDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        reportModelDto.setPremisesId(reqDto.getPremisesId());
        reportModelDto.setOrders(" t.model_order");
        List<ReportModel> list = reportModelService.selectListByDto(reportModelDto);
        int initIndex = 0;
        for(int i=0; i< list.size(); i++){
            if(reqDto.getId().equals(list.get(i).getId())){
                initIndex = i;
                continue;
            }
        }
        if(reqDto.getAction() == 0){
            //上移
            if(initIndex == 0){
                //已经在最顶端了
                moveReportModelOrderResDto.setResult(ResultEnum.FAIL.getNo());
                moveReportModelOrderResDto.setResultMsg("已经在最顶端");
                return moveReportModelOrderResDto;
            }
            //交换位置更新
            Long oldOrder = list.get(initIndex).getModelOrder();
            ReportModelDto dto = new ReportModelDto();
            dto.setId(list.get(initIndex).getId());
            dto.setModelOrder(list.get(initIndex -1).getModelOrder());
            reportModelService.update(dto);

            dto.setId(list.get(initIndex -1).getId());
            dto.setModelOrder(oldOrder);
            reportModelService.update(dto);
        }else if(reqDto.getAction() == 1){
            //下移
            if(list.size() == 1 || initIndex == list.size() -1){
                //已经在最顶端了
                moveReportModelOrderResDto.setResult(ResultEnum.FAIL.getNo());
                moveReportModelOrderResDto.setResultMsg("不能移动");
                return moveReportModelOrderResDto;
            }
            //交换位置更新
            Long oldOrder = list.get(initIndex).getModelOrder();
            ReportModelDto dto = new ReportModelDto();
            dto.setId(list.get(initIndex).getId());
            dto.setModelOrder(list.get(initIndex + 1).getModelOrder());
            reportModelService.update(dto);

            dto.setId(list.get(initIndex + 1).getId());
            dto.setModelOrder(oldOrder);
            reportModelService.update(dto);
        }
        moveReportModelOrderResDto.setResult(ResultEnum.SUCCESS.getNo());
        return moveReportModelOrderResDto;
    }

    /**
     * 根据楼盘获取报备模板列表
     * @param reqDto
     * @return
     */
    @Transactional
    public GetReportModelListResDto getReportModelList(GetReportModelListReqDto reqDto){
        GetReportModelListResDto getReportModelListRes = new GetReportModelListResDto();
        if(reqDto.getPremisesId() == null){
            getReportModelListRes.setResult(ResultEnum.SUCCESS.getNo());
            return getReportModelListRes;
        }

        ReportModelDto reportModelDto = new ReportModelDto();
        reportModelDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        reportModelDto.setPremisesId(reqDto.getPremisesId());
        reportModelDto.setModelType(reqDto.getModelType());//2为自定义
//        reportModelDto.setShowFlag(reqDto.getShowFlag());//1是0否
        reportModelDto.setOrders("t.model_type, t.model_order");
        List<ReportModel> list = reportModelService.selectListByDto(reportModelDto);

        if((list == null || list.size() == 0) && !ModelTypeEnum.customer_config.getCode().equals(reqDto.getModelType())){
            //未添加报备模板，初始化模板
            for(DefaultReportModelEnum e : DefaultReportModelEnum.values()){
                ReportModelDto ri = new ReportModelDto();
                ri.setModelColumn(e.getModelColumn());
                ri.setModelOrder(e.getModeOrder());
                ri.setModelType(e.getModelType());
                ri.setDelFlag(DelFlagEnum.UNDEL.getNo());
                ri.setPremisesId(reqDto.getPremisesId());
                ri.setShowFlag("1");//默认显示
                reportModelService.create(ri);
                list.add(ri);
            }
        }

        getReportModelListRes.setList(reportModelService.selectListByDto(reportModelDto));
        getReportModelListRes.setResult(ResultEnum.SUCCESS.getNo());

        return getReportModelListRes;

    }

    /**
     * 添加模板
     * @param list
     */
    public void setReportModeInfo(List<ReportModelInfoDto> list,Long reportId){
        if(reportId == null ){
            return;
        }
        for(ReportModelInfoDto rmi : list){
            ReportModelInfoDto rmid = new ReportModelInfoDto();
            rmid.setModelId(rmi.getModelId());
            rmid.setReportId(reportId);
            rmid.setModelColumn(rmi.getModelColumn());
            rmid.setContent(rmi.getContent());
            rmid.setDelFlag(DelFlagEnum.UNDEL.getNo());
            reportModelInfoService.create(rmid);
        }
    }

    /**
     * 添加模板
     * @param list
     */
    public void addReportModeInfo(List<ReportModelInfo> list,Long reportId){
        if(reportId == null ){
            return;
        }
        for(ReportModelInfo rmi : list){
            ReportModelInfoDto rmid = new ReportModelInfoDto();
            rmid.setModelId(rmi.getModelId());
            rmid.setReportId(reportId);
            rmid.setContent(rmi.getContent());
            rmid.setDelFlag(DelFlagEnum.UNDEL.getNo());
            reportModelInfoService.create(rmid);
        }
    }

    /**
     * 获取自定义报备模板详细信息
     * @param reqDto
     * @return
     */
    public GetReportModelInfoListResDto getReportModeInfoList(GetReportModelInfoListReqDto reqDto){
        GetReportModelInfoListResDto resDto = new GetReportModelInfoListResDto();
        if(reqDto.getReportId() == null ){
            resDto.setResult(ResultEnum.FAIL.getNo());
            return resDto;
        }

        // 记录用户复制操作
        ReportCopyRecordDto rcrDto = new ReportCopyRecordDto();
        rcrDto.setReportId(reqDto.getReportId());
        rcrDto.setCopyUser(Long.valueOf(reqDto.getUserId()));
        rcrDto.setSystemId(reqDto.getLoginType());
        rcrDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        reportCopyRecordService.create(rcrDto);

        //获取楼盘报备模板顺序
        ReportModelDto reportModelDto = new ReportModelDto();
        reportModelDto.setOrders(" t.model_order");
        reportModelDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        reportModelDto.setPremisesId(reqDto.getPremisesId());
        List<ReportModel> reportModels = reportModelService.selectListByDto(reportModelDto);
        ReportModelInfoDto dto = new ReportModelInfoDto();
        dto.setReportId(reqDto.getReportId());
        dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<ReportModelInfo> list = reportModelInfoService.selectListByDto(dto);
        resDto.setResult(ResultEnum.SUCCESS.getNo());

        //获取楼盘配置模板
        ReportModelContentDto reportModelContent = new ReportModelContentDto();
        reportModelContent.setPremisesId(reqDto.getPremisesId());
        reportModelContent.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<ReportModelContent> reportModelContents = reportModelContentService.selectListByDto(reportModelContent);

        Map<String,Object> map = new HashMap<>();
        if(null != reportModelContents && reportModelContents.size() > 0){
            //根据配置模板设置报备复制内容
            map = setReprotModelWithConfig(list,reportModelContents.get(0),reportModels,reqDto);
        }else{
            map = setReportModelString(reportModels,reqDto,list);
        }
        if(Objects.nonNull(map.get("model"))){
            resDto.setRepotModelDetail(map.get("model").toString());
        }
        if(Objects.nonNull(map.get("customerMode"))){
            resDto.setReportModelInfoList((List)map.get("customerMode"));
        }
        return resDto;
    }

    /**
     * 根据楼盘报备模板顺序 设置值
     * @param reportModels
     * @param reqDto
     * @param list
     */
    public Map<String,Object> setReportModelString(List<ReportModel> reportModels, GetReportModelInfoListReqDto reqDto, List<ReportModelInfo> list){
        Map<String,Object> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        List<ReportModelInfoDto> reportModelInfoDtoList = new ArrayList<ReportModelInfoDto>();
        for(ReportModel rm : reportModels){
            if(rm.getModelType().equals(1)){
                ReportModelInfoDto dto = new ReportModelInfoDto();
                //基础配置
                dto.setOrders(String.valueOf(rm.getModelOrder()));
                if(DefaultReportModelEnum.MOBILE.getModelColumn().equals(rm.getModelColumn())){
                    sb.append(rm.getModelColumn() + ":" + reqDto.getMobile()+"\r\n");
                    dto.setModelColumn(DefaultReportModelEnum.MOBILE.getModelColumn());
                    dto.setContent(reqDto.getMobile());
                    dto.setId(DefaultReportModelEnum.MOBILE.getModeOrder());
                }
                if(DefaultReportModelEnum.AGENCY_NAME.getModelColumn().equals(rm.getModelColumn())){
                    sb.append(rm.getModelColumn() + ":" + reqDto.getAgencyName()+"\r\n");
                    dto.setModelColumn(DefaultReportModelEnum.AGENCY_NAME.getModelColumn());
                    dto.setContent(reqDto.getAgencyName());
                    dto.setId(DefaultReportModelEnum.AGENCY_NAME.getModeOrder());
                }
                if(DefaultReportModelEnum.AGENCY_PHONE.getModelColumn().equals(rm.getModelColumn())){
                    sb.append(rm.getModelColumn() + ":" + reqDto.getAgencyPhone()+"\r\n");
                    dto.setModelColumn(DefaultReportModelEnum.AGENCY_PHONE.getModelColumn());
                    dto.setContent(reqDto.getAgencyPhone());
                    dto.setId(DefaultReportModelEnum.AGENCY_PHONE.getModeOrder());
                }
                if(DefaultReportModelEnum.CUSTOMER_NAME.getModelColumn().equals(rm.getModelColumn())){
                    sb.append(rm.getModelColumn() + ":" + reqDto.getCustomerName()+"\r\n");
                    dto.setModelColumn(DefaultReportModelEnum.CUSTOMER_NAME.getModelColumn());
                    dto.setContent(reqDto.getCustomerName());
                    dto.setId(DefaultReportModelEnum.CUSTOMER_NAME.getModeOrder());
                }
                if(DefaultReportModelEnum.CUSTOMER_SEX.getModelColumn().equals(rm.getModelColumn())){
                    sb.append(rm.getModelColumn() + ":" + reqDto.getGenderName()+"\r\n");
                    dto.setModelColumn(DefaultReportModelEnum.CUSTOMER_SEX.getModelColumn());
                    dto.setContent(reqDto.getGenderName());
                    dto.setId(DefaultReportModelEnum.CUSTOMER_SEX.getModeOrder());
                }
                if(DefaultReportModelEnum.PREMISES_NAME.getModelColumn().equals(rm.getModelColumn())){
                    sb.append(rm.getModelColumn() + ":" + reqDto.getPremisesName()+"\r\n");
                    dto.setModelColumn(DefaultReportModelEnum.PREMISES_NAME.getModelColumn());
                    dto.setContent(reqDto.getPremisesName());
                    dto.setId(DefaultReportModelEnum.PREMISES_NAME.getModeOrder());
                }
                if(DefaultReportModelEnum.STORE_NAME.getModelColumn().equals(rm.getModelColumn())){
                    sb.append(rm.getModelColumn() + ":" + reqDto.getStoreName()+"\r\n");
                    dto.setModelColumn(DefaultReportModelEnum.STORE_NAME.getModelColumn());
                    dto.setContent(reqDto.getStoreName());
                    dto.setId(DefaultReportModelEnum.STORE_NAME.getModeOrder());
                }
                if(DefaultReportModelEnum.VISIT_TIME.getModelColumn().equals(rm.getModelColumn()) &&
                        !ReportModelShowStatusEnum.hide.getCode().equals(rm.getShowFlag())){
                    sb.append(rm.getModelColumn() + ":" + reqDto.getVisitTime()+"\r\n");
                    dto.setModelColumn(DefaultReportModelEnum.VISIT_TIME.getModelColumn());
                    dto.setContent(reqDto.getVisitTime());
                    dto.setId(DefaultReportModelEnum.VISIT_TIME.getModeOrder());
                }
                if(DefaultReportModelEnum.REPORT_TIME.getModelColumn().equals(rm.getModelColumn())){
                	sb.append(rm.getModelColumn() + ":" + reqDto.getCreateTime()+"\r\n");
                    dto.setModelColumn(DefaultReportModelEnum.REPORT_TIME.getModelColumn());
                    dto.setContent(reqDto.getCreateTime());
                    dto.setId(DefaultReportModelEnum.REPORT_TIME.getModeOrder());
                }
                if(DefaultReportModelEnum.RECOMMENDER.getModelColumn().equals(rm.getModelColumn()) &&
                        !ReportModelShowStatusEnum.hide.getCode().equals(rm.getShowFlag())){
                    String recommender = "无";
                    if(StringUtils.isNotEmpty(reqDto.getRecommenderUuid())){
                        PremisesRecommenderDto recommenderDto =  premisesRecommenderService.getPremisesRecommenderByUuid(reqDto.getRecommenderUuid());
                        recommender = recommenderDto.getUserName();
                    }
                    sb.append(rm.getModelColumn() + ":" + recommender+"\r\n");
                }
                reportModelInfoDtoList.add(dto);
            }else if(rm.getModelType().equals(2)){
                ReportModelInfoDto dto = new ReportModelInfoDto();
                dto.setOrders(String.valueOf(rm.getModelOrder()));
                dto.setModelColumn(rm.getModelColumn());
                sb.append(rm.getModelColumn()+":");
                boolean t = true;
                for(ReportModelInfo rmi : list){
                    if(rm.getId().equals(rmi.getModelId())){
                        sb.append(rmi.getContent()+"\r\n");
                        t = false;
                        dto.setContent(rmi.getContent());
                    }
                }
                //将自定义报备模板添加到数组 中用于显示
                dto.setId(rm.getId());
                reportModelInfoDtoList.add(dto);
                if(t){
                    sb.append("\r\n");
                }
            }
        }
        // 根据ID排序
        reportModelInfoDtoList = reportModelInfoDtoList.stream()
                .sorted(Comparator.comparing(ReportModelInfoDto :: getOrders)).collect(Collectors.toList());
        map.put("model",sb.toString());
        map.put("customerMode",reportModelInfoDtoList);
        return map;
    }

    /**
     * 根据楼盘获取模板复制信息
     * @param reportModelInfos
     * @param reportModelContent
     * @param reportModels
     * @return
     */
    public Map<String,Object> setReprotModelWithConfig(List<ReportModelInfo> reportModelInfos,ReportModelContent reportModelContent,List<ReportModel> reportModels,GetReportModelInfoListReqDto reqDto){
        Map<String,Object> map = new HashMap<>();
        Map<String,ReportModel> reportModelMap = reportModels.stream().collect(Collectors.toMap(ReportModel::getModelColumn, Function.identity(), (oldData, newData)->newData));
        Map<String,String> reportModelValueMap = new HashMap<>();
        List<ReportModelInfoDto> reportModelInfoDtoList = new ArrayList<ReportModelInfoDto>();
        //匹配出自定义字段对应的报备值
        for(ReportModelInfo reportModelInfo : reportModelInfos){
            if(reportModelMap.containsKey(reportModelInfo.getModelColumn())){
                ReportModelInfoDto dto = new ReportModelInfoDto();
                dto.setModelColumn(reportModelMap.get(reportModelInfo.getModelColumn()).getModelColumn());
                dto.setContent(reportModelInfo.getContent());
                dto.setId(reportModelInfo.getId());
                dto.setOrders(StringUtils.defaultIfBlank(dto.getOrders(), String.valueOf(reportModelInfo.getId())));
                reportModelInfoDtoList.add(dto);
                reportModelValueMap.put(reportModelMap.get(reportModelInfo.getModelColumn()).getModelColumn(),reportModelInfo.getContent());
            }
        }
        //匹配基础字段
        for(ReportModel rm : reportModels){
            if(rm.getModelType().equals(1)){
                ReportModelInfoDto dto = new ReportModelInfoDto();
                //基础配置
                if(DefaultReportModelEnum.MOBILE.getModelColumn().equals(rm.getModelColumn())){
                    reportModelValueMap.put(DefaultReportModelEnum.MOBILE.getModelColumn(),reqDto.getMobile());
                    dto.setModelColumn(DefaultReportModelEnum.MOBILE.getModelColumn());
                    dto.setContent(reqDto.getMobile());
                    dto.setId(DefaultReportModelEnum.MOBILE.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.MOBILE.getModeOrder()));
                }
                if(DefaultReportModelEnum.AGENCY_NAME.getModelColumn().equals(rm.getModelColumn())){
                    reportModelValueMap.put(DefaultReportModelEnum.AGENCY_NAME.getModelColumn(),reqDto.getAgencyName());
                    dto.setModelColumn(DefaultReportModelEnum.AGENCY_NAME.getModelColumn());
                    dto.setContent(reqDto.getAgencyName());
                    dto.setId(DefaultReportModelEnum.AGENCY_NAME.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.AGENCY_NAME.getModeOrder()));
                }
                if(DefaultReportModelEnum.AGENCY_PHONE.getModelColumn().equals(rm.getModelColumn())){
                    reportModelValueMap.put(DefaultReportModelEnum.AGENCY_PHONE.getModelColumn(),reqDto.getAgencyPhone());
                    dto.setModelColumn(DefaultReportModelEnum.AGENCY_PHONE.getModelColumn());
                    dto.setContent(reqDto.getAgencyPhone());
                    dto.setId(DefaultReportModelEnum.AGENCY_PHONE.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.AGENCY_PHONE.getModeOrder()));
                }
                if(DefaultReportModelEnum.CUSTOMER_NAME.getModelColumn().equals(rm.getModelColumn())){
                    reportModelValueMap.put(DefaultReportModelEnum.CUSTOMER_NAME.getModelColumn(),reqDto.getCustomerName());
                    dto.setModelColumn(DefaultReportModelEnum.CUSTOMER_NAME.getModelColumn());
                    dto.setContent(reqDto.getCustomerName());
                    dto.setId(DefaultReportModelEnum.CUSTOMER_NAME.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.CUSTOMER_NAME.getModeOrder()));
                }
                if(DefaultReportModelEnum.CUSTOMER_SEX.getModelColumn().equals(rm.getModelColumn())){
                    reportModelValueMap.put(DefaultReportModelEnum.CUSTOMER_SEX.getModelColumn(),reqDto.getGenderName());
                    dto.setModelColumn(DefaultReportModelEnum.CUSTOMER_SEX.getModelColumn());
                    dto.setContent(reqDto.getGenderName());
                    dto.setId(DefaultReportModelEnum.CUSTOMER_SEX.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.CUSTOMER_SEX.getModeOrder()));
                }
                if(DefaultReportModelEnum.PREMISES_NAME.getModelColumn().equals(rm.getModelColumn())){
                    reportModelValueMap.put(DefaultReportModelEnum.PREMISES_NAME.getModelColumn(),reqDto.getPremisesName());
                    dto.setModelColumn(DefaultReportModelEnum.PREMISES_NAME.getModelColumn());
                    dto.setContent(reqDto.getPremisesName());
                    dto.setId(DefaultReportModelEnum.PREMISES_NAME.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.PREMISES_NAME.getModeOrder()));
                }
                if(DefaultReportModelEnum.STORE_NAME.getModelColumn().equals(rm.getModelColumn())){
                    reportModelValueMap.put(DefaultReportModelEnum.STORE_NAME.getModelColumn(),reqDto.getStoreName());
                    dto.setModelColumn(DefaultReportModelEnum.STORE_NAME.getModelColumn());
                    dto.setContent(reqDto.getStoreName());
                    dto.setId(DefaultReportModelEnum.STORE_NAME.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.STORE_NAME.getModeOrder()));
                }
                if(DefaultReportModelEnum.VISIT_TIME.getModelColumn().equals(rm.getModelColumn()) &&
                        !ReportModelShowStatusEnum.hide.getCode().equals(rm.getShowFlag())){
                    reportModelValueMap.put(DefaultReportModelEnum.VISIT_TIME.getModelColumn(),reqDto.getVisitTime());
                    dto.setModelColumn(DefaultReportModelEnum.VISIT_TIME.getModelColumn());
                    dto.setContent(reqDto.getVisitTime());
                    dto.setId(DefaultReportModelEnum.VISIT_TIME.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.VISIT_TIME.getModeOrder()));
                }
                if(DefaultReportModelEnum.REPORT_TIME.getModelColumn().equals(rm.getModelColumn())){
                    reportModelValueMap.put(DefaultReportModelEnum.REPORT_TIME.getModelColumn(),reqDto.getCreateTime());
                    dto.setModelColumn(DefaultReportModelEnum.REPORT_TIME.getModelColumn());
                    dto.setContent(reqDto.getCreateTime());
                    dto.setId(DefaultReportModelEnum.REPORT_TIME.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.REPORT_TIME.getModeOrder()));
                }
                if(DefaultReportModelEnum.RECOMMENDER.getModelColumn().equals(rm.getModelColumn()) &&
                        !ReportModelShowStatusEnum.hide.getCode().equals(rm.getShowFlag())){
                    String recommender = "无";
                    if(StringUtils.isNotEmpty(reqDto.getRecommenderUuid())){
                        PremisesRecommenderDto recommenderDto =  premisesRecommenderService.getPremisesRecommenderByUuid(reqDto.getRecommenderUuid());
                        recommender = recommenderDto.getUserName();
                    }
                    reportModelValueMap.put(DefaultReportModelEnum.RECOMMENDER.getModelColumn(),recommender);
                    dto.setModelColumn(DefaultReportModelEnum.RECOMMENDER.getModelColumn());
                    dto.setContent(recommender);
                    dto.setId(DefaultReportModelEnum.RECOMMENDER.getModeOrder());
                    dto.setOrders(String.valueOf(DefaultReportModelEnum.RECOMMENDER.getModeOrder()));
                }
                if(StringUtils.isNotBlank(dto.getOrders())){
                    reportModelInfoDtoList.add(dto);
                }
            }
        }
        // 根据ID排序
        reportModelInfoDtoList = reportModelInfoDtoList.stream().sorted(Comparator.comparing(ReportModelInfoDto :: getOrders)).collect(Collectors.toList());
        //组织数据
        String detail = ChannelStringUtils.replaceLabel(reportModelContent.getContentParams(),reportModelValueMap);
        map.put("model",detail);
        map.put("customerMode",reportModelInfoDtoList);
        return map;
    }

    /**
     * 保存模板设置
     * @param reportModelReqDto
     */
    @Override
    public BatchUpdateReportModelResDto batchUpdateReportModel(BatchUpdateReportModelReqDto reportModelReqDto){
        BatchUpdateReportModelResDto resDto = new BatchUpdateReportModelResDto();
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        // 更新楼盘模板字段显示状态
        updateModelStatus(reportModelReqDto.getSourceId(), reportModelReqDto.getModelStatusList());
        //更新楼盘模板
        if(null != reportModelReqDto.getTargetIds() && reportModelReqDto.getTargetIds().size() > 0){
            reportModelService.batchUpdateReportModel(reportModelReqDto.getSourceId(),reportModelReqDto.getTargetIds());
        }
        //保存复制模板
        reportModelContentService.editPremisesModel(reportModelReqDto.getContent(),reportModelReqDto.getSourceId());
        //批量保存复制模板
        if(null != reportModelReqDto.getTargetIds() && reportModelReqDto.getTargetIds().size() > 0){
            reportModelContentService.batchUpdateModelContent(reportModelReqDto.getContent(),reportModelReqDto.getTargetIds());
        }
        // 异步推送楼盘报备模板
        v10BindService.batchPushReportModel(reportModelReqDto.getSourceId(), reportModelReqDto.getTargetIds());
        return resDto;
    }

    private void updateModelStatus(Long sourceId, List<ReportModelDto> modelStatusList){
        ReportModelDto dto = new ReportModelDto();
        dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        dto.setPremisesId(sourceId);
        List<ReportModel> list = reportModelService.selectListByDto(dto);
        Map<Long, ReportModelDto> statusMap = modelStatusList.stream().collect(Collectors.toMap(ReportModelDto::getId, Function.identity()));
        if(statusMap != null){
            for(ReportModel r : list){
                if(statusMap.get(r.getId()) != null){
                    ReportModelDto entity = new ReportModelDto();
                    entity.setId(r.getId());
                    entity.setShowFlag(statusMap.get(r.getId()).getShowFlag());
                    reportModelService.update(entity);
                }
            }
        }
    }

    /**
     * 获取楼盘报备模板
     * @param reqDto
     * @return
     */
    public GetReportModelContentResDto getReportModelContent(GetReportModelContentReqDto reqDto){
        GetReportModelContentResDto resDto = new GetReportModelContentResDto();
        if(null == reqDto.getPremisesId()){
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("楼盘信息不能为空");
            return resDto;
        }

        ReportModelContentDto dto = new ReportModelContentDto();
        dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        dto.setPremisesId(reqDto.getPremisesId());

        List<ReportModelContent> list = reportModelContentService.selectListByDto(dto);
        if(null != list && list.size() > 0){
            resDto.setContent(list.get(0));
            resDto.setResult(ResultEnum.SUCCESS.getNo());
        }else{
            resDto.setResult(ResultEnum.SUCCESS.getNo());
            resDto.setResultMsg("未设置楼盘报备模板");
        }
        return resDto;
    }

    @Override
    public BatchReportModelListResDto batchReportModelList(BatchReportModelListReqDto reqDto) {
        BatchReportModelListResDto resDto = new BatchReportModelListResDto();
        if(CollectionUtils.isEmpty(reqDto.getPremisesIds())){
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("请选择要报备的楼盘");
            return resDto;
        }
        PremisesDto entity = new PremisesDto();
        entity.setPremisesIds(reqDto.getPremisesIds());
        List<Premises> premisesList =  premisesService.selectListByDto(entity);
        if(CollectionUtils.isEmpty(premisesList)){
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("请选择要报备的楼盘，刷新后重试");
            return resDto;
        }
        ReportModelDto reportModelDto = new ReportModelDto();
        reportModelDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        reportModelDto.setPremisesIds(reqDto.getPremisesIds());
        // 需求：单独设置基本模板字段进行展示设置
        //reportModelDto.setModelType(ModelTypeEnum.customer_config.getCode());
        reportModelDto.setOrders("t.model_type, t.model_order");
        List<ReportModel> list = reportModelService.selectListByDto(reportModelDto);
        Map<Long, List<ReportModel>> map = list.stream().collect(Collectors.toMap(ReportModel ::getPremisesId,
        dto -> Lists.newArrayList(dto), (List<ReportModel> newValueList, List<ReportModel> oldValueList) ->
        {
            oldValueList.addAll(newValueList);
            return oldValueList;
        }));
        List<BatchReportPremisesModelListResDto> data = new ArrayList<>();
        for (Premises p : premisesList){
            BatchReportPremisesModelListResDto dto = new BatchReportPremisesModelListResDto();
            dto.setPremisesId(p.getId());
            dto.setPremisesName(p.getName());
            dto.setReportWay(p.getReportWay());
            if(map != null && map.size() > 0){
                dto.setReportModels(map.get(p.getId()));
            }
            data.add(dto);
        }
        resDto.setData(data);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setResultMsg(ResultEnum.SUCCESS.getDes());
        return resDto;
    }

}
